/**
 * 
 */
package evance.server.common.service;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author BaoVuong
 *
 */
@Component(value="appAuthenticationProvider")
public class AppAuthenticationProvider implements AuthenticationProvider {

	private static Logger LOGGER = Logger.getLogger(AppAuthenticationProvider.class);
	
	@Autowired
	private LoginService loginService;


	/**
	 * @param loginService
	 *            the loginService to set
	 */
	public void setLoginService(LoginServiceImpl loginService) {
		this.loginService = loginService;
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		CurrentUserDetails currentUserDetails = (CurrentUserDetails) loginService.loadUserByUsername(authentication.getName());
		if (currentUserDetails == null) {
			throw new UsernameNotFoundException("username_not_found", authentication.getName());
		}
		String passEncode = "";
		if (currentUserDetails.getPassword().equals(passEncode)) {
			AuthenticationToken result = new AuthenticationToken(authentication.getName(), authentication.getCredentials(), currentUserDetails.getAuthorities());
			result.setDetails(currentUserDetails);
			return result;
		}
		return null;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return true;//AuthenticationToken.class.isAssignableFrom(authentication);
	}

}
